import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// @ts-ignore
// import cesium from 'vite-plugin-cesium';
import { loadEnv } from 'vite'
import path from 'path';
function resolve(dir) {
	return path.join(__dirname, dir);
  }
// const serveList = new URL('./public/static/serve.json', import.meta.url).href
// https://vitejs.dev/config/
export default ({ command, mode }: any) => {
	const pictureSuffix = /\jpg|png|jpeg$/
	return defineConfig({
		base: "./",
		// plugins: [vue(), cesium()],
		plugins: [vue()],
		resolve: {
			alias: {
				'@': "/src"
			},
		},
		server: {
			port: 9527,
			strictPort: false,
			host: '0.0.0.0',
			open: true,
			proxy: {
				// '/api': {
				// 	secure: false,
				// 	target: loadEnv(mode, process.cwd()).VITE_APP_PROXY_URL, // 本地接口地址
				// 	changeOrigin: true,
				// 	rewrite: path => {
				// 		console.log(path);
				// 		return path.replace(/^\/api/, '');
				// 	}
				// },
				'/jeecg-boot': {
					secure: false,
					target: loadEnv(mode, process.cwd()).VITE_APP_PROXY_URL, // 本地接口地址
					changeOrigin: true,
					rewrite: path => {
						console.log(path);
						return path.replace(/^\//, '');
					}
				}
			}
		},
		// 省略文件后缀
		// @ts-ignore
		extensions: ['', '.js', '.json', '.vue', '.scss', '.css', '.ts'],
		// build: {
		// 	chunkSizeWarningLimit: 1600,
		// 	rollupOptions: {
		// 		output: {
		// 			manualChunks(id) {
		// 				if (id.includes('node_modules')) {
		// 					return id.toString().split('node_modules/')[1].split('/')[0].toString();
		// 				}
		// 			}
		// 		}
		// 	}
		// }
		build: {
			target: ['esnext'],
			rollupOptions: {
				output: {
					entryFileNames: `assets/[name].js`, // 入口文件
					chunkFileNames: `assets/[name]-[hash].js`, // 块文件
					// 由于此处我需要将图片资源与其他资源拆开放到相应的文件内，所以我是用函数的方式
					assetFileNames(chunkInfo) {
						// console.log(chunkInfo)
						if (chunkInfo.name) {
							// name 文件名 , ext 文件后缀名
							const [name, ext] = path.basename(chunkInfo.name).split('.')
							// 匹配后缀为图片的后缀的都放在images文件下，其他正常放到他的位置
							return pictureSuffix.test(ext.toLowerCase()) ? `assets/${name.toLowerCase()}.${ext}` : `assets/${name.toLowerCase()}-[hash].${ext}`
						}
						return ''
					},
				},
			}
		},
		chainWebpack(config) {
			// it can improve the speed of the first screen, it is recommended to turn on preload
			config.plugin("preload").tap(() => [{
				rel: "preload",
				// to ignore runtime.js
				// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
				fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
				include: "initial",
			},]);
			// vue项目打包时清除//console.log()  start
			config.optimization.minimizer("terser").tap((args) => {
				args[0].terserOptions.compress.drop_console = true;
				return args;
			});
			// vue项目打包时清除//console.log()  end
			// when there are many pages, it will cause too many meaningless requests
			config.plugins.delete("prefetch");

			// set svg-sprite-loader
			config.module.rule("svg").exclude.add(resolve("src/icons")).end();
			config.module.rule("svg").uses.clear();
			config.module.rule("svg").use("svg-sprite-loader").loader("svg-sprite-loader").options({
				symbolId: "icon-[name]"
			});
			config.module
				.rule("icons")
				.test(/\.svg$/)
				.include.add(resolve("src/icons"))
				.end()
				.use("svg-sprite-loader")
				.loader("svg-sprite-loader")
				.options({
					symbolId: "icon-[name]",
				})
				.end();

			config.when(process.env.NODE_ENV !== "development", (config) => {
				config
					.plugin("ScriptExtHtmlWebpackPlugin")
					.after("html")
					.use("script-ext-html-webpack-plugin", [{
						// `runtime` must same as runtimeChunk name. default is `runtime`
						inline: /runtime\..*\.js$/,
					},])
					.end();
				config.optimization.splitChunks({
					chunks: "all",
					cacheGroups: {
						libs: {
							name: "chunk-libs",
							test: /[\\/]node_modules[\\/]/,
							priority: 10,
							chunks: "initial", // only package third parties that are initially dependent
						},
						elementUI: {
							name: "chunk-elementUI", // split elementUI into a single package
							priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
							test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
						},
						commons: {
							name: "chunk-commons",
							test: resolve("src/components"), // can customize your rules
							minChunks: 3, //  minimum common number
							priority: 5,
							reuseExistingChunk: true,
						},
					},
				});
				// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
				config.optimization.runtimeChunk("single");
			});
		}
	})
}
